<?php
/*
 * scrumbrella - Scrum board.
 *
 * Copyright (C) 2009  Eliel C. Sardanons (LU1ALY) <eliels@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 
 */

/*!
 * \file
 * \brief Database abstraction API.
 */

require_once("MDB2.php");
require_once("config.php");
require_once("logger.php");

/*!
 * \brief Connect to the datanase specified in the configuration file.
 */
function db_connect()
{
	/* database configuration variables. */
	global $database_host;
	global $database_name;
	global $database_user;
	global $database_pass;
	global $database_engine;

	$db_connection =& MDB2::singleton("$database_engine://$database_user:$database_pass@$database_host/$database_name");
	if (db_error($db_connection)) {
		logger_fatal("Error whlie connecting to the database!: " . db_error_message($db_connection));
	}

	return $db_connection;
}

/*!
 * \brief Execute a query.
 * \param query The query to execute.
 * \returns The result set of the executed query.
 */
function db_query($query)
{
	$db_connection =& db_connect();
	if (db_error($db_connection)) {
		return $db_connection;
	}

	return $db_connection->query($query);
}

/*!
 * \brief Check if the passed result set is an error.
 * \param result A result set.
 * \retval true if it is an error.
 * \retval false if it is NOT an error.
 */
function db_error($result)
{
	if (PEAR::isError($result)) {
		return true;
	}

	return false;
}

/*!
 * \brief Get the error message of an executed query.
 * \param result A result set returned by an executed query.
 * \returns The error message.
 */
function db_error_message($result)
{
	return $result->getMessage();
}

/*!
 * \brief Fetch a row from a resultset.
 * \param result The resultset.
 * \see db_query
 * \returns an array with the information requested in the query.
 */
function db_fetchrow($result)
{
	return $result->fetchRow(MDB2_FETCHMODE_ASSOC);
}

/*!
 * \brief Returns the number of rows in a result set.
 * \param result The result set.
 * \returns The number of rows in the result set.
 * \see db_query
 */
function db_numrows($result)
{
	return $result->numRows();
}

/*! \brief free a mysql result
 *  \param $result the result set.
 */
function db_freeresult($result)
{
	$result->Free();
}
?>
